package com.Logistics.pddispatch.service.impl;

import com.Logistics.BaseFeign.Driver_jobFeignClient;
import com.Logistics.BaseFeign.Task_transportFeignClient;
import com.Logistics.BaseFeign.TransportFeignClient;
import com.Logistics.entity.DriverJob;
import com.Logistics.entity.Task_transport;
import com.Logistics.entity.TransportOrder;
import com.Logistics.truck.TrainNumberFeignClient;
import com.Logistics.truck.TransportLineFeignClient;
import com.Logistics.OrderFeignClient;
import com.Logistics.pddispatch.dto.OrderClassifyGroupDTO;
import com.Logistics.pddispatch.dto.OrderLineSimpleDTO;
import com.Logistics.pddispatch.dto.OrderLineTripsTruckDriverDTO;
import com.Logistics.dto.TaskTransportDto;
import com.Logistics.pddispatch.entity.*;
import com.Logistics.entity.line.LineBean;
import com.Logistics.entity.trainNumber.TrainNumberBean;
import com.Logistics.entity.truck.Transport_trips_truck_driverBean;
import com.Logistics.enums.OrderStatus;
import com.Logistics.enums.transporttask.TransportTaskAssignedStatus;
import com.Logistics.enums.transporttask.TransportTaskLoadingStatus;
import com.Logistics.enums.transporttask.TransportTaskStatus;
import com.Logistics.pddispatch.service.BusinessOperationService;
import com.Logistics.mycommon.tools.IDAlgorithm;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.Logistics.entity.Order;

import java.sql.Date;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class BusinessOperationServiceImpl implements BusinessOperationService {
    @Autowired
    private OrderFeignClient orderFeignClient;
    @Autowired
    private TransportFeignClient transportFeignClient;
    @Autowired
    private TrainNumberFeignClient trainNumberFeignClient;
    @Autowired
    private TransportLineFeignClient transportLineFeignClient;
    @Autowired
    private Driver_jobFeignClient driverJobFeignClient;
    @Autowired
    private Task_transportFeignClient taskTransportFeignClient;
    /**
     * 创建运输任务信息
     * @param orderLineSimpleDTOS
     * @return
     */
    @Override
    public Map<String, TaskTransportDto> createTransportOrderTask(List<OrderLineSimpleDTO> orderLineSimpleDTOS) {
        Map<String,TaskTransportDto> taskTransportMap = new HashMap<>();

        orderLineSimpleDTOS.forEach(item->{
            CacheLineDetail cacheLineDetail = item.getCacheLineDetailEntity();
            List<OrderClassifyGroupDTO> orderClassifyGroupDTOS = item.getOrderClassifyGroupDTOS();

            List<String> transportOrderIds = new ArrayList<>();
            orderClassifyGroupDTOS.forEach(orderClassifyGroupDTO -> {
                if (orderClassifyGroupDTO.isNew()){
                    //新订单
                    orderClassifyGroupDTO.getOrders().forEach(order->{
                        //更新订单状态
                        Order orderDto = new Order();
                        orderDto.setStatus(Integer.parseInt(OrderStatus.FOR_LOADING.getValue()));
                        orderDto.setId(order.getId());
                        orderFeignClient.updateOrder(orderDto);
                    });
                }
                List<String> orderIds = orderClassifyGroupDTO.getOrders().stream().map(Order::getId).collect(Collectors.toList());
                List<TransportOrder> transportOrderList = this.transportFeignClient.findByOrderIdsList(orderIds);
                transportOrderIds.addAll(transportOrderList.stream().map(TransportOrder::getId).collect(Collectors.toList()));
            });
            Task_transport task_transport = new Task_transport();
            task_transport.setId(new IDAlgorithm(0L,0L).nextIdAsString());
            task_transport.setStart_agency_id(cacheLineDetail.getStart_agency_id());
            task_transport.setEnd_agency_id(cacheLineDetail.getEnd_agency_id());
            task_transport.setStatus(TransportTaskStatus.PENDING.getCode());
            task_transport.setAssigned_status(TransportTaskAssignedStatus.TO_BE_DISTRIBUTED.getCode());
            task_transport.setLoading_status(TransportTaskLoadingStatus.HALF.getCode());
            TaskTransportDto taskTransportDto = new TaskTransportDto();
            taskTransportDto.setTask_transport(task_transport);
            taskTransportDto.setTransportOrderIds(transportOrderIds);
            taskTransportDto = this.transportFeignClient.createTaskTransport(taskTransportDto);

            taskTransportMap.put(cacheLineDetail.getTransport_line_id(),taskTransportDto);
         });

        return taskTransportMap;
    }

    /**
     * 修改运输任务信息
     * @param orderLineTripsTruckDriverDTOS
     * @param transportTaskMap
     */
    @Override
    public void updateTransportTask(List<OrderLineTripsTruckDriverDTO> orderLineTripsTruckDriverDTOS,
                                    Map<String, TaskTransportDto> transportTaskMap) {
        orderLineTripsTruckDriverDTOS.forEach(orderLineTripsTruckDriverDTO -> {
            List<Transport_trips_truck_driverBean> tripsTruckDriverBeanList = orderLineTripsTruckDriverDTO.getTripsTruckDriverDTO();
            String transportLineId = orderLineTripsTruckDriverDTO.getTransportLineId();
            tripsTruckDriverBeanList.forEach(transportTripsTruckDriverBean -> {
                TrainNumberBean trainNumberBean = this.trainNumberFeignClient.getTrainNumberById(transportTripsTruckDriverBean.getTransport_trips_id());

                String[] time = trainNumberBean.getDeparture_time().split(":");
                LocalDateTime departureDate = LocalDateTime.now().withHour(Integer.parseInt(time[0])).withMinute(Integer.parseInt(time[1])).withSecond(00);

                LineBean lineBean = (this.transportLineFeignClient.getLineById(transportLineId)).getData();
                LocalDateTime reachDate = departureDate.plusMinutes(lineBean.getEstimated_time().longValue());

                Task_transport taskTransport = transportTaskMap.get(transportLineId).getTask_transport();

                DriverJob driverJob = new DriverJob();
                driverJob.setId(new  IDAlgorithm(0L,0L).nextIdAsString());
                driverJob.setStatus(1);
                driverJob.setStart_agency_id(taskTransport.getStart_agency_id());
                driverJob.setEnd_agency_id(taskTransport.getEnd_agency_id());
                driverJob.setPlan_departure_time(Date.from(Instant.from(departureDate)));
                driverJob.setPlan_arrival_time(Date.from(Instant.from(reachDate)));
                driverJob.setCreate_time(new java.util.Date());
                this.driverJobFeignClient.addDriverJob(driverJob);

                Task_transport taskTransportUpdate = new Task_transport();
                BeanUtils.copyProperties(taskTransport,taskTransportUpdate);
                taskTransportUpdate.setAssigned_status(2);
                taskTransportUpdate.setTruck_id(transportTripsTruckDriverBean.getTruck_id());
                taskTransportUpdate.setTransport_trips_id(transportTripsTruckDriverBean.getTransport_trips_id());
                taskTransportUpdate.setPlan_departure_time(Date.from(Instant.from(departureDate)));// 计划发车时间
                taskTransportUpdate.setPlan_arrival_time(Date.from(Instant.from(reachDate)));// 计划到达时间
                taskTransportUpdate.setPlan_pick_up_goods_time(Date.from(Instant.from(departureDate)));// 计划提货
                taskTransportUpdate.setPlan_delivery_time(Date.from(Instant.from(reachDate)));// 计划交付
                taskTransportFeignClient.updateTask_transport(taskTransportUpdate);

                transportTaskMap.remove(transportLineId);
            });
        });
        transportTaskMap.forEach((lineId,taskTransport)->{
            Task_transport task_transport = new Task_transport();
            task_transport.setId(task_transport.getId());
            task_transport.setStatus(0);
            this.taskTransportFeignClient.updateTask_transport(task_transport);
        });
    }

}
